
/*
*Released on 28th June 2008.
*Any violations can be reported at paritosh@wikiocean.net
*What is treated as violations can be found at www.wikiocean.net/ppl1-voilations*
******************************************************************************
* The contents of this file are subject to POOL Public License 1.0 and later.
* POOL Public License is based on Affero GPL v3 and additional conditions.
* ("License"); You may not use this file except in compliance with the License
* You may obtain a copy of the Affero GPL v3 License at http://www.gnu.org/licenses/agpl.html
* You may obtain a copy of the POOL Public License 1.0 or later at www.wikiocean.net/license/ppl.html
* Software distributed under POOL Public License 1.0 is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
* The Initial Developer of the Original Code is Paritosh Pungaliya (C) 2008. All Rights Reserved.
******************************************************************************
* Objective of the additional terms (license)
* 1) Is to extend the software freedom to freedom to work.
* 2) To ensure that knowledge is free from monopoly of agencies.
* 3) To avoid a situation where big corporate or investor can buy out free software groups and companies and then start milking the communities built around it.
* (this trend can be seen how the freedom is curtailed in companies that get Venture Capital funding.)
******************************************************************************
*/

package  logger;

// ProcessLogger Contains --> Msg_id Parent_id Request Process	Source(table Name)	Data	DateTime	Status

import java.io.*;
import java.util.*;
import java.text.SimpleDateFormat;

import utility.*;
import database.RecordSearch;
import dbmanager.*;
import file.FileOperation;
import file.FileUtility;


public class ProcessLogger
{	
	
	FileUtility fu;
	GetIdName getIdName;
	
	final String MSG_ID = "msgid";	
	final String REQUEST = "request";
	final String PROCESS = "process";	
	final String DATE = "date";
	final String STATUS = "status";
	final String SCHEDULEDATE="scheduledate";
	final String DATA = "data";
	final String MASTEROBJECT = "masterobject";
	final String USERNAME = "username";
	final String TYPE="mastertype";
	final String PRODUCT="product";	
	final String tablename= "eventprocess";
	final String DATETIME= "datetime";
	GetIdName gin;
	
	Hashtable<Object, Object> inithash = new Hashtable<Object, Object>();
		
	MyDate date;
		
	Date now = Calendar.getInstance().getTime();
	SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
	String currentDate=formatter.format(now.getTime()).toString();
    
	

	String LogDir = Input.PROCESSLOGGERPATH;	
	Date datetime;
	FileWriter fwrite;
	String loggerpath;
	
	String arr1Clmn[];
	String Msg_id;	
	PoolLogger pl;
	
	public ProcessLogger()
	{
		inithash.put(MSG_ID, MSG_ID);    	
    	inithash.put(REQUEST, REQUEST);
    	inithash.put(PROCESS, PROCESS);
    	inithash.put(REQUEST, REQUEST);
    	inithash.put(DATE, DATE);
    	inithash.put(STATUS, STATUS);
    	inithash.put(DATA, DATA);
    	inithash.put(USERNAME, USERNAME);    	
    	
    	
    	gin = new GetIdName();
    	
    	// logger
		pl = (PoolLogger) PoolLogger.getLogger(this.getClass().getName());
		
    	File temp = new File(LogDir);
    	if(temp.exists()==false)
    		temp.mkdirs();
    }

	
	public void addLog(String Msg_id, String Request, String Process, String Data, String Username,String Product,String Type,String datetime)
	{	
		try
		{
			formatter = new SimpleDateFormat("dd-MM-yyyy dd:mm:ss");
			String currentDateTime = formatter.format(now.getTime()).toString();			
	    	System.out.println (inithash);
		try
			{
				Hashtable<Object,Object> event = new Hashtable<Object,Object>();
				event.put(MSG_ID, Msg_id);
				event.put(PROCESS, Process);
				event.put(REQUEST,Request);		// get this field from meta data of database i.e. name of the table
				event.put(STATUS,"0");
		    	event.put(DATA, Data);
		    	event.put(DATETIME, datetime);
		    	event.put(USERNAME, Username);
		    	event.put(PRODUCT, Product);
		    	event.put(TYPE, Type);
				Hashtable<Object,Object> condition = new Hashtable<Object,Object>();
				getIdName = new GetIdName();
				String getIdOfEvent = getIdName.getId("Event");
				String getIdOfProcess = getIdName.getId(Process);
				int pv_index = Column.pv_index-1;
				int vt_index = Column.vt_index-1;
				int ref_index = Column.ref_index-1;
				
				condition.put("pid", getIdOfEvent);
				condition.put("mid", Type);
				condition.put("td", "null");
				RecordSearch ps = new RecordSearch();
				ps.setConditionMap(condition);
				String temp[] = ps.getArrayFromResultSet();
				//temp = sortArrayIndex(temp, ref_index); 
				condition.clear();	
				for (int i=0; i<temp.length; i++)
				{
					String record[] = temp[i].split("\t");
					condition.put("mid",record[pv_index]);
					condition.put("pid", getIdOfProcess);
					condition.put("td", "null");
					ps.setConditionMap(condition);
					String line[] = ps.getArrayFromResultSet();
					line = sortArrayIndex(line, ref_index);
					for(int j=0;j<line.length;j++)
					{
						String splitline[] = line[j].split("\t");
						String value=splitline[pv_index];
						event.put(MASTEROBJECT, value);
						event = ConvertToLower.convertHashKey(event);
						DBManager.getInsert(tablename, event);
					}	
				}
			}
			catch(Exception e){
				e.printStackTrace();
			}
		}
		catch(Exception e)
		{
			System.out.println("logger::ProcessLogger:: addLog()::error ");
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings("unchecked")
	public void updateLog (String Msg_id, String Parent_id, String Request, String Status)
	{
		formatter = new SimpleDateFormat("dd-MM-yyyy DD:MM:SS");
		String currentDateTime = formatter.format(now.getTime()).toString();
		Hashtable<Object, Object> htip = new Hashtable<Object, Object>();	

		try
		{	
			htip.put(MSG_ID, Msg_id);	    	
	    	htip.put(REQUEST, Request);	    		    		    	
	    	loggerpath = LogDir+currentDate+Input.FILRFORMAT;
			
	    	inithash.put(STATUS, Status);
			inithash.put(DATE, currentDateTime);
			
			DBManager.getUpdate(tablename,inithash,htip);
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
	
	public String[] sortArrayIndex(String[] recordSet,int indexOfField) 
	{
		int min = 0;
		
		for(int j=0;j<recordSet.length;j++)
		{
			int indexOfSort = 0;
			
			String []Values = recordSet[j].split("\t");
			try
			{
				indexOfSort = Integer.parseInt(gin.getItem(Values[indexOfField]));
			}
			catch (Exception e)
			{
				indexOfSort=0;
			}
			
			min = indexOfSort;
			int Precedence = 0;
			for(int i=j+1;i<recordSet.length;i++)
			{
				String splitrecordSet[]=recordSet[i].split("\t");
				try
				{
					Precedence = Integer.parseInt(gin.getItem(splitrecordSet[indexOfField]));
				} catch (Exception e) 
				{
					Precedence =0;
				}
				if(min > Precedence)
				{
					String temp = recordSet[j];
					recordSet[j] = recordSet[i];
					recordSet[i] = temp;
					min = Precedence;
				}
			}
		}
		return recordSet;
	}
	
	public void deleteLogRecord (String Msg_id, String Parent_id, String Request, String Status)
	{
		Hashtable<Object, Object> htip = new Hashtable<Object, Object>();	
		try
		{	
			this.Msg_id = Msg_id;
			htip.put(MSG_ID, Msg_id);	    	
	    	htip.put(REQUEST, Request);
	    	htip.put(STATUS, Status);
	    		    		    	
	    	File dir = new File(LogDir);
			if(dir.exists())
				dir.mkdir();
						
			loggerpath = LogDir+currentDate+Input.FILRFORMAT;
			
			file.FileWriter filewriter = new file.FileWriter(loggerpath,"rws");
			FileOperation fo = new FileOperation(filewriter.fileOpen());
			fo.deleteFileRecord(htip);
			filewriter.fileClose();
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
	}
		
	public static void main (String args[])
	{
		ProcessLogger processLogger = new ProcessLogger();
	//	processLogger.addLog("1",  "add", "master", "ok done","+911234567891","pool","person");
		
	}
}